package scan.config;

import org.apache.shardingsphere.core.yaml.swapper.ShardingRuleConfigurationYamlSwapper;
import org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.Primary;
import scan.properties.RuleProperties;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Configuration
@Import(value ={RuleProperties.class} )
@ConditionalOnClass(name = {"org.apache.shardingsphere.shardingjdbc.api.ShardingDataSourceFactory"})
public class ShardingJdbcConfig {
    //路由配置
    @Autowired
    private RuleProperties shardingRule;

    @Autowired
    private DataSource firstDataSource;

    @Autowired
    private DataSource secondDataSource;

    @Bean
    @Primary
    public DataSource datasource() throws Exception{
        Map<String, DataSource> dataSourceMap = new HashMap<>();
        dataSourceMap.put("db0", firstDataSource);
        dataSourceMap.put("db1", secondDataSource);
        Properties properties = new Properties();
        properties.setProperty("sql.show", String.valueOf(true));
        DataSource dataSource = ShardingDataSourceFactory.createDataSource(dataSourceMap,
                new ShardingRuleConfigurationYamlSwapper().swap(shardingRule) ,properties);
        return dataSource;
    }

}
